package com.example.home7;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class InternalStorage extends Fragment {
    public InternalStorage() {
        super(R.layout.internal);
    }
    private final String FILE_NAME = "Internal.txt";
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getView().findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    BufferedWriter bw = new BufferedWriter(
                            new OutputStreamWriter(
                                    getActivity().openFileOutput(FILE_NAME, Context.MODE_PRIVATE)));
                    bw.write("HelloWorld");
                    bw.close();
                    Toast.makeText(getActivity(), "内部写入成功", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        getView().findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(getActivity().openFileInput(FILE_NAME)));
                    Toast.makeText(getActivity(), br.readLine(), Toast.LENGTH_SHORT).show();
                    //注意 这样只能读取一行·
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
